﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Linq.Dynamic;
using System.Text;
using System.Threading.Tasks;
using Abp;
using Abp.Application.Services.Dto;
using Abp.Authorization;
using Abp.AutoMapper;
using Abp.Configuration;
using Abp.Domain.Repositories;
using Abp.Extensions;
using Abp.Linq.Extensions;
using LeadThing.AbpZeroTemplate.SupportingSystems.Authorization;
using LeadThing.AbpZeroTemplate.SupportingSystems.Dtos;
using LeadThing.AbpZeroTemplate.Dto;
using LeadThing.AbpZeroTemplate.Files;
using LeadThing.AbpZeroTemplate.Files.Dtos;
using LeadThing.AbpZeroTemplate.Areas;

namespace LeadThing.AbpZeroTemplate.SupportingSystems
{
    /// <summary>
    /// 配套制度服务实现
    /// </summary>
    [AbpAuthorize(SupportingSystemAppPermissions.SupportingSystem)]


    public class SupportingSystemAppService : AbpZeroTemplateAppServiceBase, ISupportingSystemAppService
    {
        private readonly IRepository<SupportingSystem, long> _supportingSystemRepository;
        private readonly ISupportingSystemListExcelExporter _supportingSystemListExcelExporter;
        private readonly IRepository<File, long> _fileRepository;
        private readonly IRepository<Area, long> _areaRepository;



        private readonly SupportingSystemManage _supportingSystemManage;
        /// <summary>
        /// 构造方法
        /// </summary>
        public SupportingSystemAppService(IRepository<SupportingSystem, long> supportingSystemRepository,
SupportingSystemManage supportingSystemManage
      , ISupportingSystemListExcelExporter supportingSystemListExcelExporter, IRepository<File, long> fileRepository, IRepository<Area, long> areaRepository
  )
        {
            _supportingSystemRepository = supportingSystemRepository;
            _supportingSystemManage = supportingSystemManage;
            _supportingSystemListExcelExporter = supportingSystemListExcelExporter;
            _fileRepository = fileRepository;
            _areaRepository = areaRepository;
        }


        #region 实体的自定义扩展方法
        private IQueryable<SupportingSystem> _supportingSystemRepositoryAsNoTrack => _supportingSystemRepository.GetAll().AsNoTracking();


        #endregion


        #region 配套制度管理

        /// <summary>
        /// 根据查询条件获取配套制度分页列表
        /// </summary>
        public async Task<PagedResultDto<SupportingSystemListDto>> GetPagedSupportingSystemsAsync(GetSupportingSystemInput input)
        {

            var query = _supportingSystemRepositoryAsNoTrack;
            //TODO:根据传入的参数添加过滤条件
            if (!string.IsNullOrWhiteSpace(input.Filter))
                query = query.Where(p => p.SystemTitle.Contains(input.Filter));

            var supportingSystemCount = await query.CountAsync();

            var supportingSystems = await query
            .OrderByDescending(p => p.Id)
            .PageBy(input)
            .ToListAsync();


            var areaList = _areaRepository.GetAll();
            var fileList = _fileRepository.GetAll();
            return new PagedResultDto<SupportingSystemListDto>(supportingSystemCount,
                supportingSystems.Select(item =>
                {
                    var dto = item.MapTo<SupportingSystemListDto>();
                    var townModel = areaList.Where(p => p.Id == dto.TownID).Select(p => new { p.Title }).FirstOrDefault();
                    if (townModel != null)
                        dto.TownTitle = townModel.Title;

                    var areaModel = areaList.Where(p => p.Id == dto.AreaID).Select(p => new { p.Title }).FirstOrDefault();
                    if (areaModel != null)
                        dto.AreaTitle = areaModel.Title;

                    var villModel = areaList.Where(p => p.Id == dto.VillageID).Select(p => new { p.Title }).FirstOrDefault();
                    if (villModel != null)
                        dto.VillageTitle = villModel.Title;

                    var fileModel = fileList.Where(p => p.Id == dto.FileID).Select(p => new { p.Title }).FirstOrDefault();
                    if (fileModel != null)
                        dto.FileTitle = fileModel.Title;

                    return dto;
                }).ToList());

        }

        /// <summary>
        /// 通过Id获取配套制度信息进行编辑或修改 
        /// </summary>
        public async Task<GetSupportingSystemForEditOutput> GetSupportingSystemForEditAsync(NullableIdDto<long> input)
        {
            var output = new GetSupportingSystemForEditOutput();

            SupportingSystemEditDto supportingSystemEditDto;

            if (input.Id.HasValue)
            {
                var entity = await _supportingSystemRepository.GetAsync(input.Id.Value);
                supportingSystemEditDto = entity.MapTo<SupportingSystemEditDto>();
            }
            else
            {
                supportingSystemEditDto = new SupportingSystemEditDto();
            }

            output.SupportingSystem = supportingSystemEditDto;
            return output;
        }


        /// <summary>
        /// 通过指定id获取配套制度ListDto信息
        /// </summary>
        public async Task<SupportingSystemListDto> GetSupportingSystemByIdAsync(EntityDto<long> input)
        {
            var entity = await _supportingSystemRepository.GetAsync(input.Id);

            return entity.MapTo<SupportingSystemListDto>();
        }







        /// <summary>
        /// 新增或更改配套制度
        /// </summary>
        public async Task CreateOrUpdateSupportingSystemAsync(CreateOrUpdateSupportingSystemInput input)
        {
            if (input.SupportingSystemEditDto.Id.HasValue)
            {
                await UpdateSupportingSystemAsync(input.SupportingSystemEditDto);
            }
            else
            {
                await CreateSupportingSystemAsync(input.SupportingSystemEditDto);
            }
        }

        /// <summary>
        /// 新增配套制度
        /// </summary>
        [AbpAuthorize(SupportingSystemAppPermissions.SupportingSystem_CreateSupportingSystem)]
        public virtual async Task<SupportingSystemEditDto> CreateSupportingSystemAsync(SupportingSystemEditDto input)
        {
            //TODO:新增前的逻辑判断，是否允许新增

            var entity = input.MapTo<SupportingSystem>();

            entity = await _supportingSystemRepository.InsertAsync(entity);
            return entity.MapTo<SupportingSystemEditDto>();
        }

        /// <summary>
        /// 编辑配套制度
        /// </summary>
        [AbpAuthorize(SupportingSystemAppPermissions.SupportingSystem_EditSupportingSystem)]
        public virtual async Task UpdateSupportingSystemAsync(SupportingSystemEditDto input)
        {
            //TODO:更新前的逻辑判断，是否允许更新

            var entity = await _supportingSystemRepository.GetAsync(input.Id.Value);
            input.MapTo(entity);

            await _supportingSystemRepository.UpdateAsync(entity);
        }

        /// <summary>
        /// 删除配套制度
        /// </summary>
        [AbpAuthorize(SupportingSystemAppPermissions.SupportingSystem_DeleteSupportingSystem)]
        public async Task DeleteSupportingSystemAsync(EntityDto<long> input)
        {
            //TODO:删除前的逻辑判断，是否允许删除

            var model = _supportingSystemRepository.FirstOrDefault(input.Id);
            await _fileRepository.DeleteAsync(model.FileID);

            await _supportingSystemRepository.DeleteAsync(input.Id);
        }

        /// <summary>
        /// 批量删除配套制度
        /// </summary>
        [AbpAuthorize(SupportingSystemAppPermissions.SupportingSystem_DeleteSupportingSystem)]
        public async Task BatchDeleteSupportingSystemAsync(List<long> input)
        {
            //TODO:批量删除前的逻辑判断，是否允许删除
            await _supportingSystemRepository.DeleteAsync(s => input.Contains(s.Id));
        }

        #endregion

        #region 配套制度的Excel导出功能


        public async Task<FileDto> GetSupportingSystemToExcel()
        {
            var entities = await _supportingSystemRepository.GetAll().ToListAsync();

            var dtos = entities.MapTo<List<SupportingSystemListDto>>();

            var fileDto = _supportingSystemListExcelExporter.ExportSupportingSystemToFile(dtos);



            return fileDto;
        }


        #endregion

    }
}
